"use client";

import React, { useState, useEffect, useRef } from "react";
import { Message } from "@/components/message";
import { Header } from "@/components/header";
import { ThemeProvider } from "@/components/ui/theme";
import { SettingsDialog } from "@/components/settings-dialog";
import { MessageSquare, Send, Loader2 } from "lucide-react";
import { Input } from "@/components/ui/input";

interface ApiResponse {
  role: "user" | "assistant";
  content: string;
}

interface StreamResponse {
  role: "assistant";
  content: string;
}

export function ChatContainer() {
  const [messages, setMessages] = useState<ApiResponse[]>([]);
  const [input, setInput] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isSettingsOpen, setIsSettingsOpen] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };
  
  useEffect(() => {
    // 首先从服务器获取默认设置
    const fetchDefaultSettings = async () => {
      try {
        const response = await fetch('/api/settings');
        if (response.ok) {
          const settings = await response.json();
          console.log("Default settings loaded from server:", settings);
          
          // 检查本地存储中是否已有设置，如果没有则使用默认值
          if (typeof window !== 'undefined') {
            const storedApiKey = localStorage.getItem("apiKey");
            const storedApiEndpoint = localStorage.getItem("apiEndpoint");
            const storedIsLocalApi = localStorage.getItem("isLocalApi") === "true";
            
            let isLocalApiEndpoint = false;
            
            // 如果有端点设置，判断是否是本地 API
            if (storedApiEndpoint) {
              isLocalApiEndpoint = storedApiEndpoint.includes('localhost') || 
                                   storedApiEndpoint.includes('127.0.0.1');
              
              if (!storedIsLocalApi) {
                localStorage.setItem("isLocalApi", String(isLocalApiEndpoint));
              }
            } else if (settings.apiEndpoint) {
              // 使用服务器设置
              isLocalApiEndpoint = settings.apiEndpoint.includes('localhost') || 
                                   settings.apiEndpoint.includes('127.0.0.1');
              localStorage.setItem("apiEndpoint", settings.apiEndpoint);
              localStorage.setItem("isLocalApi", String(isLocalApiEndpoint));
            }
            
            // 如果没有密钥设置但服务器有提供，使用服务器设置
            if (!storedApiKey && settings.apiKey) {
              localStorage.setItem("apiKey", settings.apiKey);
            }
            
            // 检查设置是否有效：如果是本地 API，则不需要密钥
            const apiKey = storedApiKey || settings.apiKey || "";
            const apiEndpoint = storedApiEndpoint || settings.apiEndpoint || "";
            const isValidSettings = apiEndpoint.trim() && 
                                   (isLocalApiEndpoint || apiKey.trim());
            
            if (!isValidSettings) {
              console.log("API settings not found or invalid, opening settings dialog");
              setIsSettingsOpen(true);
    }
          }
        } else {
          throw new Error("Failed to load default settings");
        }
      } catch (error) {
        console.error("Error loading default settings:", error);
        
        // 错误时回退到检查 localStorage
        if (typeof window !== 'undefined') {
          const apiKey = localStorage.getItem("apiKey") || "";
          const apiEndpoint = localStorage.getItem("apiEndpoint") || "";
          const isLocalApi = localStorage.getItem("isLocalApi") === "true" || 
                             apiEndpoint.includes('localhost') || 
                             apiEndpoint.includes('127.0.0.1');
  
          // 检查设置是否有效
          const isValidSettings = apiEndpoint.trim() && (isLocalApi || apiKey.trim());
          
          if (!isValidSettings) {
            console.log("API settings not found or invalid, opening settings dialog");
            setIsSettingsOpen(true);
          }
        }
      }
    };
    
    fetchDefaultSettings();
  }, []);
  
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleSubmit = async (e?: React.FormEvent) => {
    if (e) {
      e.preventDefault();
    }
    if (!input.trim() || isLoading) return;

    // 获取 API 设置
    let apiKey = "";
    let apiEndpoint = "";
    let isLocalApi = false;
    
    try {
      if (typeof window !== 'undefined') {
        apiKey = localStorage.getItem("apiKey") || "";
        apiEndpoint = localStorage.getItem("apiEndpoint") || "";
        isLocalApi = localStorage.getItem("isLocalApi") === "true";
      }
      
      // 如果本地存储中没有设置，尝试从服务器获取
      if (!apiEndpoint) {
        const response = await fetch('/api/settings');
        if (response.ok) {
          const settings = await response.json();
          apiEndpoint = settings.apiEndpoint || "";
          apiKey = settings.apiKey || "";
          isLocalApi = apiEndpoint.includes('localhost') || apiEndpoint.includes('127.0.0.1');
          
          // 保存到本地存储以备将来使用
          if (typeof window !== 'undefined' && apiEndpoint) {
            localStorage.setItem("apiEndpoint", apiEndpoint);
            if (apiKey) localStorage.setItem("apiKey", apiKey);
            localStorage.setItem("isLocalApi", String(isLocalApi));
          }
        }
      }
    } catch (error) {
      console.error("Error fetching API settings:", error);
    }
  
    // 检查 API 设置是否有效
    const isValidSettings = apiEndpoint.trim() && (isLocalApi || apiKey.trim());
    
    // 如果仍然没有有效的 API 设置，打开设置对话框
    if (!isValidSettings) {
      console.log("API settings not found or invalid, opening settings dialog");
      setIsSettingsOpen(true);
      return;
    }
    
    const userMessage: ApiResponse = { role: "user", content: input };
    setMessages((prev) => [...prev, userMessage]);
    setInput("");
    setIsLoading(true);

    try {
      // 构建请求 headers，如果是本地 API 且没有密钥，则不包含 Authorization 头
      const headers: HeadersInit = {
        "Content-Type": "application/json",
      };
      
      if (apiKey.trim()) {
        headers["Authorization"] = `Bearer ${apiKey}`;
      }
      
      // 获取模型名称，默认使用 "deepseek-r1:7b"
      let modelName = "deepseek-r1:7b";
      
      try {
        // 尝试从本地存储或服务器获取模型名称
        if (typeof window !== 'undefined') {
          const storedModel = localStorage.getItem("modelId");
          if (storedModel) {
            modelName = storedModel;
          } else {
            // 如果本地没有，尝试从服务器获取
            const settingsResponse = await fetch('/api/settings');
            if (settingsResponse.ok) {
              const settings = await settingsResponse.json();
              if (settings.model) {
                modelName = settings.model;
                localStorage.setItem("modelId", modelName);
              }
            }
          }
        }
      } catch (error) {
        console.error("Error fetching model name:", error);
      }
      
      // 构建请求体，为本地 Ollama API 添加 model 参数
      const requestBody: any = {
        messages: [...messages, userMessage],
      };
      
      // 如果是本地 API (Ollama)，需要添加 model 参数
      if (isLocalApi) {
        // Ollama API 格式与其他API不同，需要重新格式化
        requestBody.model = modelName;
        
        // Ollama API 需要特定格式的消息
        requestBody.messages = [...messages, userMessage].map(msg => ({
          role: msg.role === "user" ? "user" : "assistant",
          content: msg.content
        }));
        
        // Ollama 还需要 stream 参数来启用流式输出
        requestBody.stream = true;
        }
        
      const response = await fetch(apiEndpoint, {
        method: "POST",
        headers,
        body: JSON.stringify(requestBody),
      });

      if (!response.ok) {
        throw new Error(`API request failed: ${response.statusText}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("Response body is not readable");
      }

      let assistantMessage = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        try {
          // Ollama的流式响应是多个JSON对象，每个都以换行符结束
          // 处理可能包含多个响应的块
          const lines = chunk.split('\n').filter(line => line.trim() !== '');
          
          for (const line of lines) {
            try {
              const data = JSON.parse(line);
              
              // Ollama的响应格式不同，需要检查它的格式
              if (data.message) {
                // Ollama格式
                assistantMessage += data.message.content || '';
              } else if (data.content) {
                // 标准流式响应格式
                assistantMessage += data.content;
                }
                
              setMessages((prev) => {
                const newMessages = [...prev];
                const lastMessage = newMessages[newMessages.length - 1];
                if (lastMessage && lastMessage.role === "assistant") {
                  lastMessage.content = assistantMessage;
                } else {
                  newMessages.push({ role: "assistant", content: assistantMessage });
              }
                return newMessages;
              });
            } catch (lineError) {
              console.error("Error parsing JSON line:", lineError);
            }
          }
        } catch (e) {
          console.error("Error processing chunk:", e);
        }
      }
    } catch (error) {
      console.error("Error:", error);
      setMessages((prev) => [
        ...prev,
        { role: "assistant", content: "抱歉，发生了错误。请稍后重试。" },
      ]);
    } finally {
      setIsLoading(false);
    }
  };
  
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
      e.preventDefault();
      handleSubmit();
    }
  };
  
  return (
    <ThemeProvider defaultTheme="system">
      <div className="flex flex-col h-screen bg-slate-50 dark:bg-slate-950 text-slate-900 dark:text-slate-100">
        <Header onOpenSettings={() => setIsSettingsOpen(true)} />
        
        <div className="flex-1 overflow-hidden container max-w-4xl mx-auto px-3 md:px-4 py-4 flex flex-col gap-4">
          <div 
            className="flex-1 overflow-y-auto custom-scrollbar rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 shadow-sm h-[calc(100vh-11rem)]" 
          >
            {messages.length === 0 ? (
              <div className="empty-chat">
                <div className="empty-chat-icon">
                  <MessageSquare size={48} strokeWidth={1.5} />
                </div>
                <h3 className="text-lg font-medium mb-2 text-slate-800 dark:text-slate-100">开始一个新对话</h3>
                <p className="text-sm max-w-md text-slate-600 dark:text-slate-300">
                  通过提问开始与DeepSeek模型对话。您可以询问任何问题，我将尽力提供帮助。
                </p>
              </div>
            ) : (
              <div className="messages-wrapper p-3 md:p-4 flex flex-col gap-1">
                {messages.map((message, index) => (
                  <Message
                    key={index}
                    message={message}
                  />
                ))}
                <div ref={messagesEndRef} />
              </div>
            )}
          </div>
          
          <div className="relative">
            <div className="relative">
              <textarea
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder="输入消息..."
                disabled={isLoading}
                rows={1}
                className="min-h-[56px] max-h-[200px] w-full resize-none rounded-xl border-2 border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-4 py-3.5 pr-14 text-slate-700 dark:text-slate-200 focus:outline-none focus:ring-0 focus:border-blue-400 dark:focus:border-blue-500 disabled:opacity-70 placeholder:text-slate-400 dark:placeholder:text-slate-500 text-base custom-scrollbar"
              />
              <button
                onClick={(e) => {
                  e.preventDefault();
                  handleSubmit();
                }}
                disabled={!input.trim() || isLoading}
                className={`absolute bottom-2.5 right-3 rounded-full p-2 
                  ${input.trim() && !isLoading 
                    ? "bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white" 
                    : "bg-slate-200 text-slate-400 dark:bg-slate-700 dark:text-slate-500"
                  } 
                  transition-all duration-200 disabled:cursor-not-allowed`}
                aria-label="发送消息"
              >
                {isLoading ? (
                  <Loader2 className="h-5 w-5 animate-spin" />
                ) : (
                  <Send className="h-5 w-5" />
                )}
              </button>
            </div>
            <div className="mt-2 flex items-center justify-center gap-1 text-xs text-slate-500 dark:text-slate-400">
              <span>按</span>
              <kbd className="px-1.5 py-0.5 rounded-md bg-slate-100 dark:bg-slate-800 font-sans border border-slate-200 dark:border-slate-700 shadow-sm">Ctrl</kbd>
              <span>+</span>
              <kbd className="px-1.5 py-0.5 rounded-md bg-slate-100 dark:bg-slate-800 font-sans border border-slate-200 dark:border-slate-700 shadow-sm">Enter</kbd>
              <span>发送消息</span>
            </div>
          </div>
        </div>
        
        <SettingsDialog 
          open={isSettingsOpen} 
          onOpenChange={setIsSettingsOpen}
        />
      </div>
    </ThemeProvider>
  );
} 